const sys = require(`./system.js`)
const title = '基金分红提醒'
const $ = sys.$(title)

sys.run($, 'task:one', (resList, cookie, index, username, password, item) => {
    return new Promise(async resolve => {
        const page = item.page
        const size = 50
        const rate = 15
        console.log('配置信息', {
          page: page,
          size: size,
          rate: rate,
        })

        // 查询转卖列表
        const resp1 = await $.publicJS.buyTransferList($, cookie, page, size)
        const data = resp1.items.data
        console.log('data.length', data.length)

        // 过滤奖励列表
        const list = data.filter(it => it.equities.rate === rate)
        console.log('fList.length', list.length)

        // 存在 15% 权益 发送提醒
        if(list.length > 0) {
          const deadLineStr = list[0].equities.deadLine.substring(0, 10)
          const tDay = parseInt((new Date(deadLineStr) - new Date()) / 60 / 60 / 24 / 1000)
          const awardAmount = list[0].awardAmount
          const awardRate = list[0].awardRate
          //  \n${deadLineStr} 持仓结束。额奖 ${awardAmount} 元，额比 ${awardRate * 100}%
          resList.push(`${(page - 1) * size} ~ ${page * size} 基金 \n持仓 ${tDay} 天 \n额奖 ${awardAmount} 元`)
          setPage(item, 1)
        } else {
          // 最后一页。则从 1 开始
          if(data.length !== size) {
            setPage(item, 1)
          } else {
            setPage(item, page + 1)
          }
        }
        return resolve(resList)
    })
}, (resList) => {
    console.log('任务结束 resList:', resList)
    const resListStr = JSON.stringify(resList, null, 2)
    if(resList && resList.length > 0) {
        let count = $.localStorage.get('task:jj-count', 'localStorageInfo') || 0
        console.log('count1.length', count)
        count = count + 1
        console.log('count2.length', count)
        $.localStorage.set('task:jj-count', count, 'localStorageInfo')
        //if(count <= 3) {
          //$.notify.sendNotify(title, resList[0] + `\n${count} 次`)
        $.notify.sendNotify(title, resList[0])
        //}
    }
})

function setPage(item, page) {
  item.page = page
  const dbItem = $.localStorage.get('task:one', 'localStorage')
  if(item.page !== dbItem.page) {
    $.localStorage.set('task:one', [item], 'localStorage')
  }
}

